<?php
/*
 * Game related functions
 * 
 * 
 */
 
//seconds required to refresh each activegame
//in each refresh, players in the game is scanned and check if they're online
//if they're offline, they are removed from the game.
//It is attempted to refresh everytime it receives a request from user
define('game_refresh_time',4,true);//60

//seconds required to timeout a game(one day) and archive
define('game_inactive_timeout',86400,true); //86400

//other constants
//maximum players a room can hold
define('maximum_players',10,true);//maximum number of players allowed

//seconds required to refresh activegames table
define('gamerooms_refresh_time',15,true);//15s



 
//game links
$game_prefix = $index_page . "?game=";
	$game_join = $game_prefix . "join";
	$game_updategamerooms =$game_prefix . "updategamerooms";
	$game_trycreategame  = $game_prefix . "trycreategame";
	$game_trydeletegame = $game_prefix . "trydeletegame";
	$game_tryrefreshgame = $game_prefix . "tryrefreshgame";
	$game_tryupdategame = $game_prefix . "tryupdategame";
	$game_solved = $game_prefix . "solved";
 
	//select a single record from activegames table
	//returns $game
	function selectSingleFromActivegames($what,$whereKey,$whereVal,$otherConds=""){
		$result = select($what,table_activegames,$whereKey,$whereVal,$otherConds);
		if ($result){
			return $result[0];
		}else {
			return false;
		}
	}
	
	//select a single record from gamesets table
	//returns $gameset
	function selectSingleFromGamesets($what,$whereKey,$whereVal,$otherConds=""){
		$result = select($what,table_gamesets,$whereKey,$whereVal,$otherConds);
		return $result[0];
	}

 	//update activegames table in database
 	function updateActiveGames($gameid,$updateItem,$updateValue){
		return updateSingleField(table_activegames,"gameid",$gameid,$updateItem,$updateValue);
	}
	
	//delete a record from acivegames table
	function deleteFromActivegames(&$game){
		$gameid = $game['gameid'];
		$result = delete(table_activegames,"gameid",$gameid);
		return $result;
	}
	
	//reset lastplayedgame of players from activegames table
	function resetLastplayedgameOfPlayers(&$game){
		$players=explode(";",$game['players']);
		foreach($players as &$user){
			$user=getUserById($user);
			if ($user['lastplayedgameid']==$game['gameid']){
				resetLastPlayedGame($user);
			}
			if ($user['lastcreatedgameid']==$game['gameid']){
				resetCreatedGame($user);
			}		
		}
	}


	//game related database functions
	//$gameid -> $game
	function getGameByGameid($gameid){
		return selectSingleFromActivegames("*","gameid",$gameid);
	}

	//add a user to players in activegames
	//$user,$game -> boolean	
	function addUserToPlayers(&$user,&$game){
		$gameid=$game['gameid'];
		$userid=$user['id'];
		$players=$game['players'];
		$players_exploded =explode(";",trim($players,";"));  //convert players to array
		if ($players==null){
			$players=$userid;
		} else {
			if (!in_array($userid,$players_exploded)){ //if player is not in the list of players
				$players_exploded[]=$userid;
				$players = implode(";",$players_exploded);
			}
		}
		$game['players']=$players;
		//update user lastplayedgame
		setLastplayedgame($user,$game);
		//update activegames table
		$result = updateActivegames($gameid,"players",$players);
		return $result;
	}
	
	//remove a user from players from activegames
	//$user, $game -> boolean
	function removeUserFromPlayers(&$user,&$game){
		$gameid=$game['gameid'];
		$userid=$user['id'];
	
		$players=$game['players'];
		$players_exploded=explode(";",trim($players,";"));  //convert players to array
		if (in_array($userid,$players_exploded)){ //if player is in the list
			foreach ($players_exploded as $id){ //append to array if they are different players
				if ($userid!=$id){
					$newplayers[]=$id;
				}
			}
			if(!isset($newplayers)){
				$players=null;
			} else {
				$players=implode(";",$newplayers);
			}
		}
		$game['players']=$players;	
		$result = updateActivegames($gameid,"players",$players);
		return $result;	
	}
	
	//ask user to join an activegame
	//
	//$user, $game -> boolean
	function letUserJoinGame(&$user,&$game){
		$userid=$user['id'];
		$gameid=$game['gameid'];
		//update last played gameid
		$updateUsers = updateUsers($userid,"lastplayedgameid",$gameid);
		$addUserToPlayers = addUserToPlayers($user,$game);
		if ($updateUsers && $addUserToPlayers){
			return true;
		} else {
			return false;
		}
	}


	//convert playerid string from activegames (players) to 
	//array of users,
	//loginname's separated by ; 
	//id's separated by ;
	//or nickname's  separated by ;
	function translatePlayersToUsers($players,$separator=null,$key="nickname"){
		if ($players){
			$players_exploded=explode(";",$players);
			foreach ($players_exploded as &$player){
				$user=getUserById($player);
				if($key!=null){
					$player=$user[$key];
				} else {
					$player=$user;
				}
			}
			if ($separator==null){
				return $players_exploded;
			} else {
				return implode($separator,$players_exploded);
			}
		} else {
			return null;
		}
	}

	function getRandomGameset($difficulty){
		return selectSingleFromGamesets("*","difficulty",$difficulty,
					"ORDER BY RAND() LIMIT 1");
	}
	
	//create a new game in activegames and return the gameid
	function createNewGame($gamename,$gamedesc,$creatorid,$difficulty){
		$randomgame = getRandomGameset($difficulty);
		if ($randomgame) {
			$gamestate=$randomgame['unsolved'];
			$gamesetid=$randomgame['id'];
			$difficulty=$randomgame['difficulty'];
			$time=time();
			
			//create new chat session for game
			$chatid=createNewChatSession();
				
			$query="INSERT INTO `".table_activegames."` " .
				"(`gamename`, `description`, `gamestate`, `difficulty`, `gamesetid`, `creatorid`, `lastactivity`, `movehistory`, `chatlogid`) " .
				"VALUES('$gamename', '$gamedesc', '$gamestate', '$difficulty', '$gamesetid', '$creatorid', '$time', '$creatorid:0,0', '$chatid');";
			
			if(mysql_query($query)){
				$gameid=mysql_insert_id();
				$updateUsers = updateUsers($creatorid,"lastcreatedgameid",$gameid);
				return $gameid;
			} else {
				return false;
			}
		} else {
			die("Could not select random game.");
		}
	}
	
	//get the status of game
	//$gameid -> boolean (active/inactive)
	function getGameStatus($gameid){
		if (isset($gameid)){
			$game = getGameByGameid($gameid);
			if (isset($game) && $game){
				$lastactivity = $game['lastactivity'];
				if (time()-$lastactivity>game_inactive_timeout){//if last activity is more than timeout,
					return false;
				} else {
					return true;
				}
			}
		}
		return false;
	}
	
	//get number of players in an activegame
	//$game -> number of players
	function getNumPlayersInGame(&$game){
		$players=$game['players'];
		$exploded=explode(";",$players);
		if ($exploded[0]!=null){
			return count($exploded);
		}
		return 0;
	}
	
	//get the list of activegames
	//returns array(activegames)
	function getActivegames(){
		//we cannot selectSingleFromActivegames since we need 
		//to mysql_fetch_array later
		$result=select("*",table_activegames,"","","ORDER BY `gameid` DESC");
		return $result;
	}

	//get the number of moves left to finish in a game
	//$game -> number of moves left
	function getMovesleft(&$game){
		$gamestate = $game['gamestate'];
		$i = 0;
		$movesdone = str_replace("0","",$gamestate,$i);
		return $i;
	}
	
	//set new players in activegames table
	//$game, $newplayers(string of userids) -> boolean
	function setGamePlayers(&$game,$newplayers){
		$result = updateActiveGames($game['gameid'],"players",$newplayers);
		return $result;		
	}
	
	//set new gamestate in activegames table
	//$game, $newgamestate(string of numbers) -> boolean
	function setGamestate(&$game,$newgamestate){
		$result = updateActiveGames($game['gameid'],"gamestate",$newgamestate);
		return $result;
	}
	
	//updates the last refreshtime of game
	//$game -> boolean
	function updateGameRefreshtime(&$game){
		$result = updateActiveGames($game['gameid'],"lastrefreshed",time());
		return $result;
	}
	
	//updates the last activity of game
	//$game -> boolean
	function updateGameLastactivity(&$game){
		$time=time();
		$game['lastactivity']=$time;
		$result = updateActiveGames($game['gameid'],"lastactivity",$time);
		return $result;	
	}
	
	//to check the online status of players in a game
	//set remove users if they're offline
	// no return value
	function refreshPlayersInGame(&$game){
		$players=$game['players'];
		if(isset($players) && $players){
			$playersAry=translatePlayersToUsers($players,null,null);
			foreach($playersAry as $user){
				if (!getUserStatus($user)){
					removeUserFromPlayers($user,$game);
				} else {
					$newAry[]=$user['id'];
				}
			}
			if (isset($newAry)){
				$newplayers= implode(";",$newAry);
			}
			$game['players']=$newplayers;
			setGamePlayers($game,$newplayers); //update activegames
		}
	}
	
	//get the string of solved gamestate
	//$game -> string of numbers
	function getSolvedGame(&$game){
		$result=selectSingleFromGamesets("*","id",$game['gamesetid']);
		if (isset($result) && $result){
			return $result['solved'];
		} else {
			return false;
		}
	}
	
	//generates a new gamename for a newly created game
	//based on last autoincrement value of activegames table
	//returns new name
	function generateGamename(){
		$result = mysql_query("SHOW TABLE STATUS LIKE '".table_activegames."';");
		$row = mysql_fetch_array($result);
		$Auto_increment = $row['Auto_increment'];
		return "Sudoku $Auto_increment";
	}
	
	//archives game
	//$game -> boolean
	function archiveGame(&$game){
		deleteFromActiveGames($game);
		
		//insert to archieve
		$gameid=$game['gameid'];
		$gamename=mysql_real_escape_string($game['gamename']);
		$description=mysql_real_escape_string($game['description']);
		$gamestate=$game['gamestate'];
		$gamesetid=$game['gamesetid'];
		$creatorid=$game['creatorid'];
		$movehistory=$game['movehistory'];
		$chatlogid=$game['chatlogid'];
		$query = "INSERT INTO `".table_archive."` " .
					"(`gameid`, `gamename`, `description`,`gamestate`,`movehistory`,`gamesetid`,`creatorid`, `chatlogid`) " .
					"VALUES('$gameid', '$gamename', '$description', '$gamestate', '$movehistory', '$gamesetid', '$creatorid', '$chatlogid');";
		$result=mysql_query($query);
		return $result;	
	}
	

	//is user's last craeted game still active?
	//$user->boolean
	function isLastcreatedgameActive($user){
		$gamestatus = getGamestatus($user['lastcreatedgameid']);

		if ($gamestatus){
			//last created game is still active
			return true;
		}
		return false;

	}
	
	//$user,$game->boolean
	function isUserCreatorOfGame(&$user,&$game){
		if ($user['id']==$game['creatorid']){
			return true;
		} else {
			return false;
		}
	}
	
	//check if the sudoku value filled in by user is correct
	//$game,$index,$value->boolean
	function isCorrectMove(&$game,$index,$value){
		$solved=str_split(getSolvedGame($game));
		if ($solved[$index]==$value){
			return true;
		} else {
			return false;
		}
	}
	
	//$game->boolean
	function isGameSolved(&$game){
		$solved=getSolvedGame($game);
		$gamestate=$game['gamestate'];
		if ($solved===$game['gamestate']){
			return true;
		} else {
			return false;
		}
	}
	
	//add user to movehistory of game
	//$user,$game->boolean(update successful?)
	function addUserToMovehistory(&$user,&$game){
		$movehistory=$game['movehistory'];
		$userid=$user['id'];
		if (isset($movehistory) && $movehistory){
			$newmovehist="$movehistory;$userid:0,0";
		} else {
			$newmovehist="$userid:0,0";
		}
		return updateActivegames($game['gameid'],"movehistory",$newmovehist);
	}
	
	//abstraction to get movehistory from users and activegames
	//$from($user/$game) -> array(difficulty=>array(correct moves,wrong moves))
	//$from($user/$game), $key -> array(correct moves,wrong moves)
	function getMovehistory(&$from,$key=null){
		$history=explode(";",$from['movehistory']);
		if(isset($history) && $history){
			foreach($history as $record){
				$exploded=explode(":",$record);
				$vals=$exploded[1];
				$vals=explode(",",$vals);
				if($exploded[0]!=null){
					$newhistory[$exploded[0]]=$vals;
				}
			}
			if ($key){
				if ($newhistory[$key]==null){
					$vals=array("0","0");
					return $vals;
				} else {
					return $newhistory[$key];
				}
			} else {
				return $newhistory;
			}
		} else {
			return false;
		}
	}
	//get movehistory of user
	// $user,$difficulty -> array(correct moves,wrong moves)
	// $user -> array(difficulty=>array(correct moves,wrong moves))
	function getMovehistUser(&$user,$diff=null){
		return getMovehistory($user,$diff);
	}
	//get movehistory of activegames
	// $game,$user -> array(correct moves,wrong moves)
	// $game -> array(userid=>array(correct moves,wrong moves))
	function getMovehistActivegames(&$game,$user=null){
		return getMovehistory($game,$user['id']);
	}
	
	//abstraction to increase move by one for movehistory of users and activegames
	function incMovehistory(&$from,$key,$wrongmove=0){
		$history=getMovehistory($from);
		$vals=$history[$key];
		if($vals[0]==null){$vals[0]=0;}
		if($vals[1]==null){$vals[1]=0;}
		$vals[$wrongmove]=$vals[$wrongmove]+1;
		$history[$key]=$vals;
		foreach($history as $hkey=>$values){
			if ($hkey!=null){
				$movepair=implode(",",$values); //correct and wrong moves pair
				$newmovehistory[]="$hkey:$movepair";
			}
		}
		$from['movehistory']=implode(";",$newmovehistory);
		return $newmovehistory;
	}
	//increase one move in movehistory of User for a difficulty
	function incMovehistoryUsers(&$user,$diff,$wrongmove=0){
		incMovehistory($user,$diff,$wrongmove);
		return updateUsers($user['id'],"movehistory",$user['movehistory']);
	}
	
	//increase one move in movehistory of activegame for a player
	function incMovehistoryActivegames(&$user,&$game,$wrongmove=0){
		incMovehistory($game,$user['id'],$wrongmove);
		return updateActivegames($game['gameid'],"movehistory",$game['movehistory']);
	}
	
	//abstraction retrieve keys from movehistory (userids for activegames, difficulties for users)
	//$from -> array(keys)
	function getKeysFromMoveHistory(&$from){
		$scores=explode(";",$from['movehistory']);
		foreach($scores as &$score){
			$exploded=explode(":",$score);
			if ($exploded[0]!=null){
				$ids[]=$exploded[0];
			}
		}
		return $ids;
	}
	
	//to retrieve userids from user movehistory
	//$game -> array(userids)
	function getUseridsFromMoveHistory(&$game){
		return getKeysFromMoveHistory($game);
	}
	
	//check if user exists in movehistory of game
	//$user,$game -> boolean
	function existUserInMovehistory(&$user,&$game){
		if ($game['movehistory']){
			$history=getUseridsFromMoveHistory($game);
			if(in_array($user['id'],$history)){
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	//check if user exists in players of activegame
	//$user,$game -> boolean
	function existUserInPlayers(&$user,&$game){
		$players=$game['players'];
		$exploded=explode(";",$players);
		if(isset($exploded) && $exploded){
			if(in_array($user['id'],$exploded)){
				return true;
			} 
		}
		return false;
	}
	
	//update score of user in users table
	//$user -> boolean
	function updateScore(&$user){
		
		$movehistory=getMovehistUser($user);
		$totalscore=0;
		foreach($movehistory as $key=>$value){
			$correct=$value[0];
			$wrong=$value[1];
			$totalscore=$totalscore+($key*$correct)-($key*$wrong);
		}
		
		$result=updateUsers($user['id'],"score",$totalscore);
	}

	//prints sudoku div cells in the page
	function printSudokuCells(){
		$counter=0;
		for($y=0;$y<9;$y++){
			for($x=0;$x<9;$x++){
				echo "<div id=cell-$counter class=cell>$counter</div>";
				$counter++;
			}
		}
	}
	
	function printSudokuInitializeScript($user,$game){
		global $game_tryupdategame;
		global $game_tryrefreshgame;
		echo "<script type='text/javascript'>";
			$gameid=$game['gameid'];
			$gamestate="\"".$game['gamestate']."\"";
			$updateurl="\"$game_tryupdategame&gameid=$gameid\"";
			$refreshurl="\"$game_tryrefreshgame&gameid=$gameid\"";
			$playertable="\"".generatePlayerlist($user,$game)."\"";
			
			$write="\$(document).ready(initializeGame($gamestate,$updateurl," .
				"$refreshurl,$playertable));";
		echo $write;
		echo "</script>";
	}
	
	//returns the table of playerlist for sidebar in the game with updated players' status
	//this function does not print
	function generatePlayerlist($user,$game){
		global $page_profile;
		$content=null;
		
		$players=getUseridsFromMoveHistory($game);
		if ($players){
			$players=implode(";",$players);
			$players=translatePlayersToUsers($players,null,null);
			
			$result="<table class=bigtable>";
			//highlighter of usernames in player list
			$result=$result."<div id=playerhighlight></div>";
			$result=$result."<tr class=heading><td></td><td></td><td>Correct</td><td>Wrong</td></tr>";
			foreach ($players as $player){
				$playerstatus=getUserStatus($player);
				if($playerstatus && existUserInPlayers($player,$game) && $player['lastplayedgameid']==$game['gameid']){
					$status="<div class=online></div>";
				} else {
					$status="<div class=offline></div>";
				}
				$result=$result."<tr><td>$status</td><td>";
				$nickname=$player['nickname'];
				$litags= "class=player fullname='$nickname'";
	
				if (strlen($player['nickname'])>8){
					//$content=$player['nickname'];
					$content=substr($player['nickname'],0,8)."...";
					
				} else {
					$content=$player['nickname'];
				}
				
				$playerid=$player['id'];
				if($playerid==$user['id']){
					$me=" [me]";
				} else { 
					$me=null;
				}
				//put link to player profiles;

				$url="$page_profile&profile=$playerid";
				$result=$result. "<a href='$url' action=_self><div $litags url='$url'>$content$me</div></a>";	
				$result=$result."</td>";
				
				$movepair=getMovehistActivegames($game,$player);
				$correct=$movepair[0];
				$wrong=$movepair[1];
				$result=$result."<td>$correct</td>";
				$result=$result."<td>$wrong</td>";
				$result=$result."</tr>";
			}
			$result=$result."</table>";
		}
		return $result;
	}
	
	//prints the table of active games
	function printActivegamesTable(){
		global $page_profile;
		global $game_join;
		
		$activegames=getActivegames();
		if($activegames){
			echo "<p class=center>or join one of the following games...</p>
				<table class='bigtable marginauto'>
				<tr class=heading>
				<td>Room name</td>
				<td>Description</td>
				<td>Difficulty</td>
				<td>Moves left</td>
				<td>Players</td>
				<td>Status</td>
				<td>Created By</td>
				<td></td>
				</tr>";
			
			foreach($activegames as $room){
				global $difficulty;
				if($room){
					$gamename = $room['gamename'];
					$gameid = $room['gameid'];
					$description = $room['description'];
					$players = translatePlayersToUsers($room['players'],null,null);
					if($players){
						foreach($players as &$player){
							$id=$player['id'];
							$nickname=$player['nickname'];
							$player="<a href='$page_profile&profile=$id' target=_self>$nickname</a>";
						}
						$players=implode(", ",$players);
					}
					$status = getGameStatus($gameid);
					if ($status){$status="Active";} else {$status="Inactive";}
					
					$diff =$difficulty[$room['difficulty']];
					$movesleft = getMovesleft($room);
					
					$creatorid = $room['creatorid'];
					$creator = getUserById($creatorid);
					$creatorname = $creator['nickname'];
					echo "<tr>";
					echo "<td>$gamename</td>";
					echo "<td>$description</td>";
					echo "<td>$diff</td>";
					echo "<td>$movesleft</td>";
					echo "<td>$players</td>";
					echo "<td>$status</td>";
					echo "<td><a href='$page_profile&profile=$creatorid' target=_self>$creatorname</a></td>";
					echo "<td><a href='$game_join&gameid=$gameid' target=_self>Join</a></td>";
					echo "</tr>";
				}
			}
			echo "</table>";
		}
	}
	
	function printActivegamesRefreshScript(){
		global $game_updategamerooms;
		$url=$game_updategamerooms;
		$gameroomsRefresh= "setInterval(\"\$('#gamerooms').load('$url');\",".(gamerooms_refresh_time*1000).")";			
		echo "<script type='text/javascript'>";
		echo "\$(document).ready($gameroomsRefresh);";
		echo "</script>";
	}
//#end of game functions


/*
 * Processing of game related requests begin here
 * First, we get the gameid sent from user and load the related game info
 * to $game.
 * $game = array(gameid,gamename,description,players,movehistory
 *               gamesetid,creatorid,lastrefreshed,lastactivity,
 *               difficulty)
 */			
//Load game info 
if (isset($_GET['gameid']) && $_GET['gameid']){
	$gameid=$_GET['gameid'];
	$game=getGameByGameid($gameid);
	//game exists
	if ($game) {
		//checks the lastactivity time of activegame
		//and archives if it is outdated
		if(!getGameStatus($game['gameid'])){
			archiveGame($game);
			$game=null;
		} else {
			updateGameLastactivity($game);
			
 			//if user just joined (is not already in) the room
			if(!existUserInPlayers($user,$game)){
			
				//if room still has space
				if(getNumPlayersInGame($game)<maximum_players){
					$oldgame=getGameByGameId($user['lastplayedgameid']);
					removeUserFromPlayers($user,$oldgame);
					
					//add user to players of activegame
					addUserToPlayers($user,$game);
					if (!existUserInMovehistory($user,$game)){
						addUserToMovehistory($user,$game);
					}
					
					
				} else { //if room has maximum players
					$page=page_gamerooms; //redirect back to gamerooms
					$submit_fail_msg="Uhh oh, this room is too crowded. <br>" .
						"We are afraid that you might now have enough room to breath.<br> " .
						"Why not try another room?";
					$game=null;
				}
			}
			
			//attemp to refresh users in the game players list
			if ((time()-$game['lastrefreshed'])>game_refresh_time){
				refreshPlayersInGame($game);
				updateGameRefreshtime($game);	
			}
					
		}
	} else {
		//if game does not exists,
		//remove game id records from $user
		if($user['lastplayedgameid']==$gameid){
			resetLastPlayedGame($user);
		}
		if($user['lastcreatedgameid']==resetCreatedGame){
			resetCreatedGame($user);
		}
	}
} else {
	if(!(isset($chataction) && $chataction!=null)){
		//user is not accessing the game related pages
		//remove user from the previous game user joined
		$oldgame=getGameByGameId($user['lastplayedgameid']);
		if ($oldgame) {
			removeUserFromPlayers($user,$oldgame);
		}
	}
}

if (isset($_GET['game'])){
	$gameaction = $_GET['game'];
	
	//process game related requests
	switch ($gameaction) {
		case 'tryupdategame': //this is an ajax request to update game
			$cellindex=$_GET['cellid'];
			$value=$_GET['cellval'];
			
			if(isset($game) && $game){
				$gs=str_split($game['gamestate']);
				
				//if cell is blank
				if($gs[$cellindex]=="0"){
					//if the move is correct
					if(isCorrectMove($game,$cellindex,$value)){
						$gs[$cellindex]=$value;
						$gamestate=implode("",$gs);
						$game['gamestate']=$gamestate;
						
						if (setGamestate($game,$gamestate)){ //update to new gamestate in table
							//increase correct move in activegame movehistory
							incMovehistoryActivegames($user,$game); 
							
							//increase correct move in user movehistory
							incMovehistoryUsers($user,$game['difficulty']);
							
							//send gamestate to client
							echo "gamestate=\"".$game['gamestate']."\";"; //send new gamestate to client
							echo "response='right';";
						}
					} else { //wrong move
						//increase wrong move in activegame movehistory
						incMovehistoryActivegames($user,$game,1);
						
						//increase wrong move in user movehistory
						incMovehistoryUsers($user,$game['difficulty'],1);
							
						//send response to client
						echo "response='wrong';";
					}
					updateScore($user);
				}
			} else { //game does not exist
				echo "response='doesnotexist';";
				echo "responseurl='$game_join'";
			}
			
			$page=page_ajax; //set page to ajax so that page.php won't print anything
			break;
		case 'tryrefreshgame': //this is an ajax request to retrieve gamestate
			if(isset($game) && $game){
				echo "gamestate=\"".$game['gamestate']."\";";
				$playerlist = generatePlayerlist($user,$game);
				echo "playerlist=\"$playerlist\";";
				
				//game solved?
				if(isGameSolved($game)){
					echo "response='solved';";
					echo "responseurl='$game_solved&gameid=".$game['gameid']."&difficulty=".$game['difficulty']."';";
					echo "clearInterval(gamerefreshId);";
				}
			} else { //game does not exist
				echo "response='doesnotexist';";
				echo "responseurl='$game_join'";
			}
			$page=page_ajax; //set page to ajax so that page.php won't print anything
			break;
			
		case 'solved'; //this is an ajax request to get congratulatory message when a game is finished
			//remove players one by one from game
			removeUserFromPlayers($user,$game);
			if ($user['lastcreatedgameid']==$game['gameid']){
				resetCreatedGame($user);
			}
			if ($user['lastplayedgameid']==$game['gameid']){
				resetLastPlayedGame($user);
			}
			
			//try to archive the game
			//if he is the last one left in the room
			if(getNumPlayersInGame($game)==0){
				archiveGame($game);
			}
			echo "solvedresponse=\"<p>With all your mighty effort, ".
				"you have solved this puzzle. ".
				"Now, have a rest. :)</p>".
			    "<a href='$game_joinrooms' target=_self>" .
			    "Another game?</a> We recommend you rest a while first.\";";
					
			//this user is not in the game anymore
			$game=null;
			
			$page=page_ajax; //set page to ajax so that page.php won't print anything
			break;
	
		case 'updategamerooms': //ajax request to refresh gamerooms table
			printActivegamesTable();
			$page=page_ajax; //set page to ajax so that page.php won't print anything
			break;
			
		//the following are non-ajax requests
		case 'trycreategame': //non ajax request
			$gamename = $_POST['roomname'];
			if ($gamename == null){
				$gamename = generateGamename();
			}
			$gamedesc = $_POST['description'];
			$diff = $_POST['difficulty'];
			
			if (!isLastcreatedgameActive($user)){
				$gameid = createNewGame($gamename,$gamedesc,$user['id'],$diff);
				if ($gameid){
					//update game info
					$game=getGameByGameid($gameid);
					letUserJoinGame($user,$game);
					
					//update user in session
					$user['lastcreatedgameid']=$gameid;
					
					$page=page_game;
					$submit_msg = 'New game created';
				} else {
					$page=page_creategame;
					$submit_fail_msg = 'For some funny reason, we could not create game. ' .
							'Perhaps you keyed in some strange characters? ' .
							'Otherwise, we will be fixing it real soon. o.O';
				}
			} else { //user is not allowed to create game because last created game is not finished
				$page=page_creategame;
				$lastcreatedgameid=$user['lastcreatedgameid'];
				$submit_fail_msg="The last game you created is not yet finished. " .
					"<a href='$game_join&gameid=$lastcreatedgameid'>Go there and finish the game first</a>. ";
			}
			break;
		case 'trydeletegame'; //non-ajax request
			$gameid=$_GET['delgameid'];
			$delgame=getGameByGameid($gameid);
			
			if ($game){
				if ($game['players']===$user['id']){
					if (isUserCreatorOfGame($user,$game)){
						//allow to delete game
						
						if (archiveGame($delgame)){
							$lastcreatedgameid=$user['lastcreatedgameid'];
							
							//reset last created game of deleter
							if ($user['lastcreatedgameid']==$delgame['gameid']){
								resetCreatedGame($user);
							}
							
							//reset last played game of user
							if ($user['lastplayedgameid']==$delgame['gameid']){
								resetLastPlayedGame($user);
							}
							$submit_msg="Game deleted :(";
							$page=page_gamerooms;
						} else {
							$page=page_game;
							$submit_fail_msg="Unable to delete the game for reasons we wonder.";
						}
					} else {
						//deletor is not creator
						$page=page_game;
						$submit_fail_msg="You are not the creator of this game. Unable to delete.";
					}
				} else {
					//other players exist in game
					$page=page_game;
					$submit_fail_msg="Unable to delete. There are players in the room";
				}
			} else {
				//game does not exist
				$page=page_gamerooms;
				$submit_fail_msg="Ah! This game has been deleted before. <br>" .
						"Not a single piece of it is left for us to delete.";	
			}
			break;
	
			
		case 'join': //check if invalid game has been requested
			if(!$game){
				$page=page_gamerooms;
				$submit_fail_msg = "Oops! This game no longer exists.<br>
					Seriously, we tried our very very best to search for it.<br>
					We even tried to use some magic.<br>
					May be it has gone inactive for 1 day or someone with bad intentions had deleted it.";
			} else {
				$page=page_game;
			}
			break;
	}
}